package com.km.uploadoss.ui.activity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.km.uploadoss.R;
import com.km.uploadoss.helper.QnUploadHelper;
import com.km.uploadoss.model.PicInfo;
import com.km.uploadoss.ui.adapter.GridImageAdapter;
import com.km.uploadoss.ui.manager.FullyGridLayoutManager;
import com.qiniu.android.http.ResponseInfo;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import io.reactivex.functions.Consumer;

public class MainActivity extends AppCompatActivity {

    RecyclerView rv_pic;
    Button btn_upload;

    String mPhotoPath;

    GridImageAdapter mAdapter;
    FullyGridLayoutManager mManager;
    List<PicInfo> mList = new ArrayList<>();

    LooperThread mLooperThread;
    RxPermissions mRxPermission;

    //七牛后台的key
    private static String mAccessKey="你的七牛AccessKey";
    //七牛后台的secret
    private static String mSecretKey="你的七牛SecretKey";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
        initAdapter();
        initListener();
    }

    private void init() {
        mRxPermission = new RxPermissions(MainActivity.this);

        rv_pic = findViewById(R.id.rv_pic);
        btn_upload = findViewById(R.id.btn_upload);
        //初始化七牛云
        QnUploadHelper.init(mAccessKey,mSecretKey);

        mLooperThread = new LooperThread();
        mLooperThread.start();
    }

    private void initAdapter() {
        mAdapter = new GridImageAdapter(this, new GridImageAdapter.OnAddPicClickListener() {
            @Override
            public void OnAddPic() {
                mRxPermission
                .requestEach(Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            // 用户已经同意该权限
                            selectPic();
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                        } else {
                            // 用户拒绝了该权限，并且选中『不再询问』
                            Toast.makeText(MainActivity.this, "无权限", Toast.LENGTH_LONG).show();
                        }
                    }
                });
            }

            @Override
            public void OnDelPic(int position) {
                mList.remove(position);
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void OnPreview(int position) {

            }
        });
        mManager = new FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        rv_pic.setLayoutManager(mManager);
        rv_pic.setAdapter(mAdapter);
        mAdapter.setPicturePathList(mList);
        mAdapter.notifyDataSetChanged();
    }

    private void initListener() {
        btn_upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int position = 0;
                for (PicInfo picInfo : mList) {
                    if(picInfo.getUploadState() == 0 || picInfo.getUploadState() == 4){
                        Message msg = Message.obtain(mLooperThread.mHandler);
                        msg.what = 0x2;
                        msg.obj = position;
                        mLooperThread.mHandler.dispatchMessage(msg);
                    }
                    position++;
                }
            }
        });
    }

    class LooperThread extends Thread {
        public Handler mHandler;

        public void run() {
            Looper.prepare();

            mHandler = new Handler() {
                public void handleMessage(Message msg) {
                    // process incoming messages here
                    switch (msg.what) {
                        case 0x2:
                            final int position = (int) msg.obj;
                            final PicInfo picInfo = mList.get(position);

                            QnUploadHelper.uploadPic(picInfo.getOriginalPath(), "upload_" + Calendar.getInstance().getTimeInMillis(), new QnUploadHelper.UploadCallBack() {
                                @Override
                                public void success(String url) {
                                    Log.i("image_url",url);
                                    picInfo.setImageUri(url);
                                }

                                @Override
                                public void fail(String key, ResponseInfo info) {
                                    Log.i("key",key+info.error);
                                    picInfo.setUploadState(3);
                                }

                                @Override
                                public void progress(String key, double percent) {
                                    Log.i("progress", key + ": " + percent);
                                    int progress = (int)(percent * 100);
                                    picInfo.setUploadProgress(progress);
                                    if(progress == 100){
                                        picInfo.setUploadState(2);
                                    }else{
                                        picInfo.setUploadState(1);
                                    }
                                    mAdapter.notifyItemChanged(position);
                                }
                            });
                            break;
                    }
                }
            };

            Looper.loop();
        }
    }

    //在选择图片后返回本界面调用此方法
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == 0x1) {
            if (data != null) {
                ContentResolver resolver = getContentResolver();
                try {
                    // 获取圖片URI
                    Uri uri = data.getData();
                    // 将URI转换为路径：
                    String[] proj = { MediaStore.Images.Media.DATA };
                    Cursor cursor = managedQuery(uri, proj, null, null, null);
                    //  这个是获得用户选择的图片的索引值
                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();
                    // 最后根据索引值获取图片路径
                    mPhotoPath = cursor.getString(column_index);

                    mList.add(new PicInfo(mPhotoPath));

                    mAdapter.notifyDataSetChanged();

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.mPhotoPath = null;
        this.mAdapter = null;
    }

    private void selectPic () {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        //打开系统提供的图片选择界面
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        //传参以在返回本界面时触发加载图片的功能
        startActivityForResult(intent, 0x1);
    }
}
